/**
 * 本地存储管理工具
 */

const STORAGE_KEYS = {
  USER_INFO: 'userInfo',
  GAME_HISTORY: 'gameHistory',
  STATISTICS: 'statistics'
};

/**
 * 保存游戏记录
 */
function saveGameRecord(record) {
  try {
    const history = getGameHistory();
    history.unshift(record);
    
    // 最多保存100条记录
    if (history.length > 100) {
      history.pop();
    }
    
    wx.setStorageSync(STORAGE_KEYS.GAME_HISTORY, history);
    
    // 更新统计数据
    updateStatistics(record);
    
    return true;
  } catch (error) {
    console.error('保存游戏记录失败:', error);
    return false;
  }
}

/**
 * 获取游戏历史记录
 */
function getGameHistory() {
  try {
    return wx.getStorageSync(STORAGE_KEYS.GAME_HISTORY) || [];
  } catch (error) {
    console.error('获取游戏记录失败:', error);
    return [];
  }
}

/**
 * 更新统计数据
 */
function updateStatistics(record) {
  try {
    const stats = getStatistics();
    
    stats.totalGames++;
    stats.totalTime += record.duration;
    stats.totalSteps += record.steps;
    stats.totalBacktracks += record.backtracks;
    
    if (record.success) {
      stats.successGames++;
      
      if (record.solveType === 'auto') {
        stats.autoSolveCount++;
      } else if (record.solveType === 'manual') {
        stats.manualSolveCount++;
      }
    }
    
    // 计算平均值
    stats.avgTime = Math.round(stats.totalTime / stats.totalGames);
    stats.avgSteps = Math.round(stats.totalSteps / stats.totalGames);
    stats.avgBacktracks = Math.round(stats.totalBacktracks / stats.totalGames);
    stats.winRate = (stats.successGames / stats.totalGames * 100).toFixed(1);
    
    // 更新最快记录
    if (record.success && record.duration < stats.fastestTime) {
      stats.fastestTime = record.duration;
    }
    
    wx.setStorageSync(STORAGE_KEYS.STATISTICS, stats);
  } catch (error) {
    console.error('更新统计数据失败:', error);
  }
}

/**
 * 获取统计数据
 */
function getStatistics() {
  try {
    const stats = wx.getStorageSync(STORAGE_KEYS.STATISTICS);
    if (stats) {
      return stats;
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
  
  // 返回默认统计数据
  return {
    totalGames: 0,
    successGames: 0,
    totalTime: 0,
    totalSteps: 0,
    totalBacktracks: 0,
    avgTime: 0,
    avgSteps: 0,
    avgBacktracks: 0,
    winRate: '0.0',
    fastestTime: Infinity,
    autoSolveCount: 0,
    manualSolveCount: 0
  };
}

/**
 * 清除所有数据
 */
function clearAll() {
  try {
    wx.removeStorageSync(STORAGE_KEYS.GAME_HISTORY);
    wx.removeStorageSync(STORAGE_KEYS.STATISTICS);
    return true;
  } catch (error) {
    console.error('清除数据失败:', error);
    return false;
  }
}

/**
 * 格式化时间
 */
function formatDuration(seconds) {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  
  if (hours > 0) {
    return `${hours}时${minutes}分${secs}秒`;
  } else if (minutes > 0) {
    return `${minutes}分${secs}秒`;
  } else {
    return `${secs}秒`;
  }
}

/**
 * 格式化日期时间
 */
function formatDateTime(timestamp) {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hour}:${minute}`;
}

module.exports = {
  saveGameRecord,
  getGameHistory,
  getStatistics,
  clearAll,
  formatDuration,
  formatDateTime
};
